from util import *

class Papers(list):
    def __init__(self, list = [], date = None):
        self[:] = list
        self.date = date

class Paper:
    # citations can be int, "notFound". "notFound" means not found on google scholar
    def __init__(self, title, authors):
        self.title = title
        self.authors = authors

    def getCitationText(self):
        return str(self.citations)

    def setCitationText(self, text):
        try:
            self.citations = int(text)
        except ValueError:
            self.citations = text

    def getDateText(self):
        return self.updateDate.isoformat()

    def setDateText(self, dateStr):
        from datetime import datetime
        self.updateDate = datetime.strptime(dateStr, "%Y-%m-%d").date()

        
def paperListToXML(paperList):
    from xml.dom.minidom import Document
    doc = Document()
    xmlpapers = doc.createElement(u"papers")
    if paperList.date != None:
        xmlpapers.setAttribute(u"date", paperList.date.isoformat())
    doc.appendChild(xmlpapers)
    for paper in paperList:
        xmlpaper = doc.createElement(u"paper")
        xmlpaper.setAttribute(u"title", paper.title)
        for author in paper.authors:
            xmlauthor = doc.createElement(u"author")
            xmlauthor.setAttribute(u"name", author)
            xmlpaper.appendChild(xmlauthor)
        if (hasattr(paper, "citations")):
            xmlpaper.setAttribute(u"citations", paper.getCitationText())
        if (hasattr(paper, "updateDate")):
            xmlpaper.setAttribute(u"updateDate", paper.getDateText())
        xmlpapers.appendChild(xmlpaper)
    return doc.toprettyxml(indent="  ", encoding="utf-8")

def XMLToPaperList(xmlFileName):
    from xml.dom.minidom import parse, parseString
    from datetime import date, datetime
    doc = parse(xmlFileName).documentElement
    papers = Papers()
    if doc.getAttribute("date") == "":
        papers.date = None
    else:
        papers.date = datetime.strptime(doc.getAttribute("date"), "%Y-%m-%d").date()
    for xmlpaper in doc.getElementsByTagName("paper"):
        title = xmlpaper.getAttribute("title")
        authors = map (lambda x: x.getAttribute("name"), \
                  xmlpaper.getElementsByTagName("author"))
        paper = Paper(title, authors)
        if (xmlpaper.hasAttribute("citations")):
            paper.setCitationText(xmlpaper.getAttribute("citations"))
        if (xmlpaper.hasAttribute("updateDate")):
            paper.setDateText(xmlpaper.getAttribute("updateDate"))
        papers.append(paper)
    return papers

import sys
import os.path
paperListPath="paperList/"
dataPath= "data/"

def conferences(root):
    for conf in os.listdir(root):
        if os.path.isdir(root + conf):
            yield conf

def statisticsFiles(root):
    for conf in conferences(root):
        if os.path.exists(root + conf + "/statistics.xml"):
            yield conf + "/statistics.xml"

            
def events(root, conf):
    for event in os.listdir(root + conf):
        if event.endswith(".xml") and event.startswith(conf):
            if os.path.isfile(root + conf + "/" + event):
                yield event

def conferenceFiles(root):
    for conf in conferences(root):
        for event in events(root, conf):
            path = conf + "/" + event
            yield path
            
            
class Event:
    pass
class Conferences:
    pass
    
def XMLToConf(xmlFileName):
    from xml.dom.minidom import parse, parseString
    from datetime import date, datetime
    doc = parse(xmlFileName).documentElement
    conf = Conferences()
    conf.name = doc.getAttribute("name")
    conf.foundedPapers = int(doc.getAttribute("foundedPapers"))
    conf.citations = int(doc.getAttribute("citations"))
    conf.impact = float(doc.getAttribute("impact"))
    conf.impactPerYear = float(doc.getAttribute("impactPerYear"))
    conf.events = []
    for eventNode in doc.getElementsByTagName("event"):
        event = Event()
        event.name = eventNode.getAttribute("name")
        event.papers = int(eventNode.getAttribute("papers"))
        event.foundedPapers = int(eventNode.getAttribute("foundedPapers"))
        event.citations = int(eventNode.getAttribute("citations"))
        event.impact = float(eventNode.getAttribute("impact"))
        event.impactPerYear = float(eventNode.getAttribute("impactPerYear"))
        event.date = None
        if eventNode.getAttribute("date") != None:
            event.date = string2date(eventNode.getAttribute("date"))
        event.usedInRanking = eventNode.getAttribute("usedInRanking") == "True"
        conf.events.append(event)
    return conf

def confToXML(conf):
    from xml.dom.minidom import Document
    doc = Document()
    xmlconf = doc.createElement("conferences")
    doc.appendChild(xmlconf)
    xmlconf.setAttribute("name", conf.name)
    xmlconf.setAttribute("foundedPapers", str(conf.foundedPapers))
    xmlconf.setAttribute("citations", str(conf.citations))
    xmlconf.setAttribute("impact", str(conf.impact))
    xmlconf.setAttribute("impactPerYear", str(conf.impactPerYear))
    for event in conf.events:
        xmlevent = doc.createElement(u"event")
        xmlconf.appendChild(xmlevent)
        xmlevent.setAttribute("name", event.name)
        xmlevent.setAttribute("papers", str(event.papers))
        xmlevent.setAttribute("foundedPapers", str(event.foundedPapers))
        xmlevent.setAttribute("citations", str(event.citations))
        xmlevent.setAttribute("impact", str(event.impact))
        xmlevent.setAttribute("impactPerYear", str(event.impactPerYear))
        if event.date != None:
            xmlevent.setAttribute("date", date2string(event.date))
        xmlevent.setAttribute("usedInRanking", str(event.usedInRanking))
    return doc.toprettyxml(indent="  ", encoding="utf-8")
